#include "Output.h"
#include "Input.h"
#include "BbsControlData.h"
#include "UserEditing.h"
#include "OverlayManagement.h"
#include "Waiting.h"
#include "Login.h"
#include "Subs.h"
#include "UserPortRS232.h"
#include "StringTable.h"
#include "Session.h"

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#include <time.h>
#include <peekpoke.h>
#include <unistd.h>
#include <device.h>


#pragma code-name ("WAITCODE");
#pragma rodata-name ("WAITCODE");
#pragma data-name("WAITDATA");
#pragma bss-name("WAITBSS");

void displayMenu(void)
{
	static FILE *file;
	static char oldDirectory[17];
	static char directory[17];
	static char filename[21];
	static int i;
	static callHistory_t callHistory;

	clrscr();

	outputFile(PLATFORM_ENCODING, OD_SCREEN, "wait.menu", &(bcd.dataDirectory));

	getcwd(oldDirectory, 17);
	getdevicedir(bcd.dataDirectory.device, directory, 17);
	chdir(directory);

	file = fopen("call-history", "rb");

	memset(&callHistory, 0, sizeof(callHistory_t));

	if(file != NULL)
	{
		if(fread(&callHistory, sizeof(callHistory_t), 1, file) == 1)
		{
			outputString(PLATFORM_ENCODING, OD_SCREEN, CRLF CHX_LGREEN "Last 10 Callers" CRLF);
			for(i = 0; i < 10 && callHistory.numberOfCallers - i > 0; ++i)
			{
				sprintf(filename, "%05u" CHX_WHITE ": " CHX_LBLUE, callHistory.numberOfCallers - i);
				outputString(PLATFORM_ENCODING, OD_SCREEN, CRLF LEAD_BLOCK CHX_ORANGE);
				outputString(PLATFORM_ENCODING, OD_SCREEN, filename);
				outputString(PLATFORM_ENCODING, OD_SCREEN, callHistory.lastUsers[i].decorated_username);
			}
		}
	}

	fclose(file);

	chdir(oldDirectory);

}

void setDateTime()
{
	static int i;
	static char c;
	static char buffer[51];
	static char part[5];
	static int hour, min, sec, month, day, year;
	static time_t newTime;
	static struct tm time;
	static struct tm *ltime;
	static time_t t;

	memset(buffer, 0, 51);
	memset(part, 0, 5);

	outputString(PLATFORM_ENCODING, OD_SCREEN, "Getting DATETIME...");

	outputString(PLATFORM_ENCODING, OD_MODEM, "att bbs.paytonbyrd.com\n");
	for(i = 0; i < 10240; i++); // delay

	//while(strlen(buffer) < 50 && (c = inputChar(PLATFORM_ENCODING, OD_MODEM, IO_ANY_CHARACTER)) != 0)
	while(strlen(buffer) < 50 && (c = readByteRS232()) != 0)
	{
		buffer[strlen(buffer)] = c;
	}

	outputString(PLATFORM_ENCODING, OD_SCREEN, buffer);
	outputString(PLATFORM_ENCODING, OD_SCREEN, CRLF);

	sscanf(buffer, "%u:%u:%u %s %u/%u/%u", 
		&hour, &min, &sec, part, &month, &day, &year);

	hour -= 1;

	if(part[0] == 'p' || part[0] == 'P') hour += 12;

	//printf("h:%u m:%u s:%u  M:%u d:%u y:%u\n",
	//	hour, min, sec, month, day, year);

	time.tm_hour = hour;
	time.tm_min = min;
	time.tm_sec = sec;
	time.tm_mon = month - 1;
	time.tm_mday = day;
	time.tm_year = year - 1900;

#ifdef __C64__
	POKE(0xDC0F, PEEK(0xDC0F) & 127);
	POKE(0xDC0B, 0x00);
	POKE(0xDC0A, 0x00);
	POKE(0xDC09, 0x00);
	POKE(0xDC08, 0x00);
#endif

	newTime = mktime(&time);

	_baseTime = newTime + 3600;

	t = _baseTime + _systime();
	ltime = localtime(&t);
	
	//printf("h:%u m:%u s:%u  M:%u d:%u y:%u\n",
	//	ltime->tm_hour, 
	//	ltime->tm_min,
	//	ltime->tm_sec,
	//	ltime->tm_mon,
	//	ltime->tm_mday,
	//	ltime->tm_year);

	memset(buffer, 0, 51);
	strftime(buffer, 51, "%I:%M:%S %p %m/%d/%Y", ltime);
	outputString(PLATFORM_ENCODING, OD_SCREEN, buffer);
	//cgetc();

}

bool initialize()
{
#ifndef __NODCD__
	static int i;
	enableRS232();

	_currentSession.sessionEncoding = EN_PETSCII;

	if(readDCD())
	{
		outputString(PLATFORM_ENCODING, OD_SCREEN, CRLF "Still connected, disconnecting now.\n");
		hangUpCall();
	}

	if(readDCD())
	{
		outputString(PLATFORM_ENCODING, OD_SCREEN, CRLF "Could not disconnect session.\n");
		return false;
	}

	outputCharacter(PLATFORM_ENCODING, OD_MODEM, '\n');
	outputCharacter(PLATFORM_ENCODING, OD_MODEM, '\n');

	clearReadBuffer();

	outputString(PLATFORM_ENCODING, OD_MODEM, "ate0v0s0=0s2=0\n");
	outputString(PLATFORM_ENCODING, OD_SCREEN, CRLF "Initializing Modem...");
	if(inputChar(PLATFORM_ENCODING, OD_MODEM, IO_ANY_CHARACTER) == '0') 
	{
		outputString(PLATFORM_ENCODING, OD_SCREEN, "Initialized Modem.\n");
		clearReadBuffer();

		if(_baseTime == 0)
		{
			setDateTime();	
		}
	}
	else
	{
		outputString(PLATFORM_ENCODING, OD_SCREEN, "MODEM ERROR.");
		clearReadBuffer();
		return false;
	}
#endif
	_connectState = CS_DISCONNECTED;

	return true;
}

void waitForCall(void)
{
	static time_t time, lastTime;
	static char buffer[41];
	char x, y, r;
#ifdef __C64__
	if((r = openRS232(2, BAUD_2400)))
#else if defined(__C128__)
	if((r = openRS232(2, BAUD_2400)) == 0)
#endif
	{
		while(!initialize());

		displayMenu();

		while(1)
		{
			time = _systime() + _baseTime;
			if(time != lastTime)
			{
				memset(buffer, 0, 41);
				strftime(buffer, 41, "%I:%M:%S %p %m/%d/%Y", localtime(&time));
				x = wherex(); y = wherey();
				lastTime = time;
			}

			revers(1);
			cputsxy(0, 0, buffer);
			revers(0);

			gotoxy(x, y);

			if(readDCD())
			{
				_connectState = CS_CONNECTED;
				outputString(PLATFORM_ENCODING, OD_MODEM, "ata\n");
				outputString(PLATFORM_ENCODING, (outDirections_t)(OD_MODEM | OD_SCREEN), "loading bbs...");
				loadOverlay("bbs.login", &login, "bbs.wait");
				initialize();
				displayMenu();
			}
			else if(kbhit())
			{
				switch(cgetc())
				{
				case CH_F1:
					_connectState = CS_CONNECTED;
#ifdef __NODCD__
					_dcd = true;
#endif
					loadOverlay("bbs.login", &login, "bbs.wait");
#ifdef __NODCD__
					_dcd = false;
#endif
					initialize();
					displayMenu();
					break;
				case CH_F3:
					_connectState = CS_CONNECTED;
#ifdef __NODCD__
					_dcd = true;
#endif
					loadOverlay("bbs.login", &loginSysop, "bbs.wait");
#ifdef __NODCD__
					_dcd = false;
#endif
					initialize();
					displayMenu();
					break;
				case CH_F5:
					loadOverlay("bbs.user", &selectUserToEdit, "bbs.wait");
					initialize();
					displayMenu();
					break;
				case CH_F6:
					loadOverlay("bbs.subs", &editSubs, "bbs.wait");
					initialize();
					displayMenu();
				case CH_F7:
					//
					break;
				case CH_F8:
					setDateTime();
					initialize();
					displayMenu();
				}
			}
		}
	}
	else
	{
		outputString(PLATFORM_ENCODING, OD_SCREEN, "Could not initialize RS232.");
	}
}